package cn.sh.system.service.impl;

import cn.sh.org.domain.Department;
import cn.sh.system.domain.Menu;
import cn.sh.system.mapper.MenuMapper;
import cn.sh.system.service.IMenuService;
import cn.sh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sh
 * @since 2022-08-14
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;


    //查询所有信息
    @Override
    public List<Menu> selectAll() {
        return menuMapper.selectAll();
    }

    @Override
    public Menu selectOne(Long id) {
        return menuMapper.selectOne(id);
    }

    //添加信息
    @Override
    @Transactional
    public void add(Menu menu) {
        menuMapper.add(menu);
        this.update(menu);
    }

    //修改信息
    @Override
    @Transactional
    public void update(Menu menu) {
       /* if (menu.getParent()==null){
            String dirPath = "/" + menu.getId();
            menu.setDirPath(dirPath);
        }else {
            Long parentId = menu.getParent().getId();
            Menu parent = menuMapper.selectOne(parentId);
            department.setDirPath(parent.getDirPath() + "/" + menu.getId());
        }*/
        menuMapper.update(menu);
    }

    //删除信息
    @Override
    @Transactional
    public void delete(Long id) {
        menuMapper.delete(id);
    }

    @Override
    @Transactional
    public void batchDelete(List ids) {
        menuMapper.batchDelete(ids);
    }
    @Override
    public List<Menu> getTree() {
        List<Menu> all = menuMapper.selectAll();//获取所有部门
        List<Menu> result = new ArrayList<>();//声明返回的集合 里面装一级部门

        HashMap<Long, Menu> hashMap = new HashMap<>();
        for (Menu menu : all) {
            hashMap.put(menu.getId(), menu);
        }

        for (Menu temp : all) {
            if (temp.getParentId() == null) {//一级部门
                result.add(temp);
            } else {//非一级部门
                Long parentId = temp.getParentId();/*获取部门的父部门id*/
                Menu parent = hashMap.get(parentId);/*根据父部门id拿到父部门对象*/
                parent.getChildren().add(temp);
            }
        }
        return result;
    }
}
